package com.sukaiyi.giteejavaapi.http.model;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author sukaiyi
 * @date 2020/06/30
 */
@Data
@NoArgsConstructor
public class HttpResponse {
    private int status;
    private Map<String, String> headers;
    private byte[] data;
    private JSONObject jsonObject;
    private JSONArray jsonArray;
    private String string;

    public JSONObject asJSONObject() {
        if (jsonObject == null) {
            synchronized (this) {
                if (jsonObject == null) {
                    String string = new String(data, StandardCharsets.UTF_8);
                    jsonObject = JSONUtil.parseObj(string);
                }
            }
        }
        return jsonObject;
    }

    public JSONArray asJSONArray() {
        if (jsonArray == null) {
            synchronized (this) {
                if (jsonArray == null) {
                    String string = new String(data, StandardCharsets.UTF_8);
                    jsonArray = JSONUtil.parseArray(string);
                }
            }
        }
        return jsonArray;
    }

    public String asString() {
        if (string == null) {
            synchronized (this) {
                if (string == null) {
                    string = new String(data, StandardCharsets.UTF_8);
                }
            }
        }
        return string;
    }

    public byte[] asByteArray(){
        return data;
    }

    public boolean success(){
        return status / 100 == 2;
    }
}